package com.itheima.web.response; /**
 * @author Xiao
 * @date 2021/8/30
 */

import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "ResponseDemo04", value = "/resp04")
public class ResponseDemo04 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        //1. 读取文件
        FileInputStream fis = new FileInputStream(
                "D:\\develop\\IdeaProjects\\JavaWeb\\mavenfiles\\request_response\\src\\main\\webapp\\imgs\\a.JPG");
        //2. 获取response字节输出流
        ServletOutputStream sos = response.getOutputStream();
        //3. 完成流的copy
        //3.1 使用字节数组
        /*byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {
            sos.write(bytes,0,len);
        }*/
        //3.2 使用工具类
        IOUtils.copy(fis, sos);
        fis.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
